<?php





namespace app\crm\model;



use think\facade\Db;

use app\admin\model\Common;



class ReturnVistT extends Common

{



    /**

     * 为了数据库的整洁，同时又不影响Model和Controller的名称

     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀

     */

    protected $name = 'return_vist_t';



    /**

     * 列表

     * @param  array $request 请求参数

     * @return array

     */

    public function getDataList(array $request): array

    {

        try {

            $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

            $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;



            $where = [];

           

            $shop_id     = $request['shop_id'] ?? 0;

            $list_type   = $request['list_type'] ?? 0;

            $customer_id = $request['customer_id'] ?? 0;

            $customer_name = $request['customer_name'] ?? 0;

            $telephone = $request['telephone'] ?? '';

            $start_time  = $request['start_time'] ?? '';

            $end_time    = $request['end_time'] ?? '';

            $market_id   = $request['market_id'] ?? 0;

            $result_id   = $request['result_id'] ?? 0;

            $user_id   = $request['user_id'] ?? 0;

            $early_warning_result   = $request['early_warning_result'] ?? '';

            $accountability_result   = $request['accountability_result'] ?? '';



            if ($shop_id > 0) {

                array_push($where,['shop_id','=',$shop_id]);

            }



            if ($customer_id > 0) {

                array_push($where,['customer_id','=',$customer_id]);

            }

            

            if ($customer_name > 0) {

                $customerIds  = Db::name('customer')->where('customer_name','like','%'.$customer_name.'%')->column('id');

                array_push($where,['customer_id','in',$customerIds]);

            }

            if ($telephone) {

                $customerIds  = Db::name('customer')->where('telephone','like','%'.$telephone.'%')->column('id');

                array_push($where,['customer_id','in',$customerIds]);

            }



            if (!empty($start_time)) {

                array_push($where,['return_visit_time','>=',strtotime($start_time.' 00:00:00')]);

            }



            if (!empty($end_time)) {

                array_push($where,['return_visit_time','<=',strtotime($start_time.' 23:59:59')]);

            }

            

            if (!empty($result_id)) {

                array_push($where,['result_id','=',$result_id]);

            }



            if ($market_id > 0) {

                $shopIds = Db::name('shop')->where('market_id','=',$market_id)->column('shop_id');

            }



            if (in_array($list_type,array(1,2,3))) {

                // code...

                if ($list_type == 3) {

                    // code...

                    array_push($where,['early_warning','=',1]);

                } else if ($list_type == 2) {

                    // code...

                    array_push($where,['accountability','=',1]);

                }

            }else{

                $data              = [];

                $data['list']      = [];

                $data['dataCount'] = 0;

                return $data;

            }

            $export = $request['export'] ?? 0;

            if ($export == 1){

                $ids = $request['id'] ?? [];

                array_push($where,['id','in',$ids]);

            }

            $shopIds = $request['shopIds'] ?? [];

            if($shopIds){

                array_push($where,['shop_id','in',$shopIds]);

            }

            if($early_warning_result!=''){
                array_push($where,['early_warning_result','=',$early_warning_result]);
            }

            if($accountability_result!=''){
                array_push($where,['accountability_result','=',$accountability_result]);
            }

            $dataCount = $this->where($where)->count();

            if($user_id == 1){

                // print_r($this->getLastSql());exit;

            }

            

            if ($dataCount) {

                $list  = $this->where($where)->order('id DESC')

                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                    ->select()->toArray();

                //获取店铺信息

                $shopIds = array_unique(array_column($list, 'shop_id'));

                $shopList  = Db::name('shop')->where('shop_id', 'in', $shopIds)->column(['shop_name','market_name'], 'shop_id');

                

                //获取相关员工信息

                $userIds1 = array_unique(array_column($list, 'handler_id'));

                $userIds2 = array_unique(array_column($list, 'return_visitor'));

                $userIds3 = array_unique(array_column($list, 'nurse_id'));

                // $userIds  = array_merge($userIds1,$userIds2,$userIds3);

                $userIds  = array_merge($userIds1,$userIds2);

                $userList  = Db::name('admin_user')->where('id', 'in', $userIds)->column(['realname'], 'id');

                // 获取店铺员工数据

                $nurseList  = Db::name('shop_person')->where('id', 'in', $userIds3)->column(['name'], 'id');

                // 客户数据

                $customerIds = array_unique(array_column($list, 'customer_id'));

                $customerList  = Db::name('customer')->where('id', 'in', $customerIds)->column('customer_name,telephone,cj_time,cj_money,member_classification', 'id');

                //获取问题分类

                $settingList  = Db::name('setting')->where('category_id', 'in', [9,11])->column(['name'], 'id');

                foreach ($list as $key => $val) {

                    $list[$key]['market_name'] = $shopList[$val['shop_id']]['market_name'] ?? '';

                    // print_r($val['nurse_id']);

                    // print_r($userList);

                    $list[$key]['shop_name']   = $shopList[$val['shop_id']]['shop_name'] ?? '';

                    $list[$key]['nurse_name']   = $nurseList[$val['nurse_id']] ?? '';

                    $list[$key]['handler_name']   = $userList[$val['handler_id']] ?? '';

                    $list[$key]['customer_name']   = $customerList[$val['customer_id']]['customer_name'] ?? '';

                    $list[$key]['telephone']   = $customerList[$val['customer_id']]['telephone'] ?? '';

                    $list[$key]['return_name']   = $userList[$val['return_visitor']] ?? '';

                    $list[$key]['setting_name']   = $settingList[$val['setting_id']] ?? '';

                    $list[$key]['result_name']   = $settingList[$val['result_id']] ?? '';

                    $list[$key]['early_warning_time']   = $val['early_warning_time'] ? date('Y-m-d H:i:s',$val['early_warning_time']) : '';

                    $list[$key]['accountability_time']   = $val['accountability_time'] ? date('Y-m-d H:i:s',$val['accountability_time']) : '';

                    $list[$key]['return_visit_time']   = $val['return_visit_time'] ? date('Y-m-d H:i:s',$val['return_visit_time']) : '';

                }

            }



            $data              = [];

            $data['list']      = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            $data['aaa'] = $early_warning_result;

            return $data;

        } catch (\Exception $e) {

            $this->error = '暂无此数据';

            return [];

        }



    }

    /**

     * 列表

     * @param  array $request 请求参数

     * @return array

     */

    public function addData(array $request): array

    {

        try {

        //     // print_r($request);exit;

            $addData['customer_id']    = $request['customer_id'] ?? 0;

            $addData['return_visitor'] = $request['user_ids'] ?? 0;

            $addData['nurse_id'] = $request['nurse_id'] ?? 0;

            $addData['shop_id']  = $request['shop_id'] ?? 0;

            $addData['result']   = $request['result'] ?? 0;

            $addData['return_visitor']    = $request['return_visitor'] ?? 0;

            $addData['service_attitude']  = $request['service_attitude'] ?? 0;

            $addData['operation_process'] = $request['operation_process'] ?? 0;

            $addData['return_visit_content'] = $request['return_visit_content'] ?? '';

            $addData['effect']   = $request['effect'] ?? 0;

            $addData['hygiene']  = $request['hygiene'] ?? 0;

            $addData['total']    = $request['total'] ?? 0;

            $addData['remarks']  = $request['remarks'] ?? '';

            $addData['setting_id']     = $request['setting_id'] ?? 0;

            $type = $request['early_warning'] ?? 0;

            if(!in_array($type,[1,2,0])){

                $this->error = '回访预警/追责类型错误';

                return [];

            }

            if($type == 0){

                $addData['early_warning']  = 0;

                $addData['accountability'] = 0;

                $addData['early_warning_content']   = '';

                $addData['accountability_content']  = '';

            }else if($type == 1){

                $addData['early_warning']  = 1;

                $addData['accountability'] = 0;

                $addData['early_warning_content']   = $request['early_warning_content'] ?? '';

                $addData['accountability_content']  = '';

            }else if($type == 2){

                $addData['early_warning']  = 0;

                $addData['accountability'] = 1;

                $addData['early_warning_content']   = '';

                $addData['accountability_content']  = $request['accountability_content'] ?? '';

            }

            

            $addData['result_id']  = $request['result_id'] ?? 0;

            $addData['effect_problem_id']  = $request['effect_problem_id'] ?? 0;

            $addData['service_issues_id']  = $request['service_issues_id'] ?? 0;

            if ($addData['setting_id'] == 0) {

                // code...

                $this->error = '问题分类不能为空';

                return [];

            }

            if ($addData['customer_id'] == 0) {

                // code...

                $this->error = '请选择回访的客户';

                return [];

            }

            if ($addData['nurse_id'] == 0) {

                // code...

                $this->error = '请选择客户的护理师';

                return [];

            }

            if ($addData['customer_id'] == 0) {

                // code...

                $this->error = '请选择回访的店铺';

                return [];

            }

            if ($addData['result'] == 0 || !in_array($addData['result'],array(1,2,3,4,5))) {

                // code...

                $this->error = '请选择回访结果';

                return [];

            }

            if ($addData['early_warning'] == 1 && empty($addData['early_warning_content'])) {

                // code...

                $this->error = '请录入预警的内容';

                return [];

            }

            if ($addData['accountability'] == 1 && empty($addData['accountability_content'])) {

                // code...

                $this->error = '请录入追责的内容';

                return [];

            }

            if ($addData['effect_problem_id'] == 0) {

                // code...

                $this->error = '效果问题不能为空';

                return [];

            }

            if ($addData['service_issues_id'] == 0) {

                // code...

                $this->error = '服务问题不能为空';

                return [];

            }

            $addData['create_time']       = time();

            $addData['return_visit_time'] = time();

            // print_r($addData);exit;

            $id = $this->insertGetId($addData);

            return ['id'=>$id];

        } catch (\Exception $e) {

            $this->error = '添加失败';

            return [];

        }



    }



    public function saveData(array $request): array

    {

        try {

            $type            = $request['type'] ?? 0;

            $result_content  = $request['result_content'] ?? '';

            $id  = $request['id'] ?? 0;

            $user_id  = $request['user_id'] ?? 0;

            $find = $this->where('id','=',$id )->find();

            if (!$find) {

                // code...

                $this->error = '数据不存在';

                return [];

            }

            if (!in_array($type,array(1,2))) {

                // code...

                $this->error = '类型错误';

                return [];

            }

            if (empty($result_content)) {

                // code...

                $this->error = '处理内容不能为空';

                return [];

            }

            $name = $type == 2 ? 'early_warning' : 'accountability';

            if ($find[$name] != 1) {

                // code...

                $this->error = '该回访无需处理';

                return [];

            }

            $saveData[$name.'_result'] = 1;

            $saveData[$name.'_time'] = time();

            $saveData[$name.'_huifu'] = $result_content;

            $saveData['handler_id'] = $user_id;

            $this->where('id','=',$id )->update($saveData);

            return ['id'=>$id];

        } catch (\Exception $e) {

            $this->error = '处理失败';

            return [];

        }

    }



    public function addReturnVistTLog(array $request): array

    {

        try {

            $user_id = $request['user_id'] ?? 0;

            $images  = $request['iamges'] ?? [];

            $content = $request['content'] ?? 0;

            $rvt_id  = $request['rvt_id'] ?? '';

            if (empty($content)) {

                // code...

                $this->error = '请输入跟进内容';

                return [];

            }

            if (empty($rvt_id)) {

                // code...

                $this->error = '暂无回访数据';

                return [];

            }

            if (is_array($images)){

                $images_str = implode(',',$images);

            }else{

                $images_str = $images;

            }

            $addData['user_id'] = $user_id;

            $addData['images']  = $images_str;

            $addData['content'] = $content;

            $addData['rvt_id']  = $rvt_id;

            Db::name('return_vist_t_log')->insertGetId($addData);

            return ['id'=>$rvt_id];

        } catch (\Exception $e) {

            $this->error = '处理失败';

            return [];

        }

    }



    public function readReturnVistT(array $request): array

    {

        try {

            $id = $request['id'] ?? 0;

            if ($id == 0) {

                $this->error = '获取失败';

                return [];

            }

            $find  = $this->where('id','=',$id) ->find()->toArray();

            //获取店铺信息

            $shopList  = Db::name('shop')->where('shop_id', '=', $find['shop_id'])->find();

            //获取相关员工信息

            $userList  = Db::name('admin_user')->where('id', 'in', [$find['handler_id'],$find['return_visitor']])->column(['realname'], 'id');

            //客户数据

            $customerList  = Db::name('customer')->where('id', '=', $find['customer_id'])->find();

            // 获取店铺员工数据

            $nursename  = Db::name('shop_person')->where('id', '=', $find['nurse_id'])->value('name');

            // print_r($customerList);exit;

            //获取问题分类

            $settingList  = Db::name('setting')->where('category_id', 'in', [9,11,12,13])->column(['name'], 'id');

            $find['market_name']   = $shopList['market_name'] ?? '';

            $find['shop_name']     = $shopList['shop_name'] ?? '';

            $find['nurse_name']    = $nursename ?? '';

            $find['handler_name']  = $userList[$find['handler_id']] ?? '';

            $find['return_name']   = $userList[$find['return_visitor']] ?? '';

            $find['setting_name']  = $settingList[$find['setting_id']] ?? '';

            $find['customer_name'] = $customerList['customer_name'] ?? '';

            $find['result_name']   = $settingList[$find['result_id']] ?? '';

            $find['effect_problem_name'] = $settingList[$find['effect_problem_id']] ?? '';

            $find['service_issues_name'] = $settingList[$find['service_issues_id']] ?? '';

            $find['early_warning_time']   = $find['early_warning_time'] ? date('Y-m-d H:i:s',$find['early_warning_time']) : '';

            $find['accountability_time']   = $find['accountability_time'] ? date('Y-m-d H:i:s',$find['accountability_time']) : '';

            $find['return_visit_time']   = $find['return_visit_time'] ? date('Y-m-d H:i:s',$find['return_visit_time']) : '';

            $list = Db::name('return_vist_t_log')->where('rvt_id','=',$id)->order('id desc')->select()->toArray();

            $ids = array_unique(array_column($list,'user_id'));

            $userList  = Db::name('admin_user')->where('id', 'in', $ids)->column(['realname'], 'id');

            foreach ($list as $key => $val){

                $list[$key]['user_name'] = $userList[$val['user_id']] ?? '';

                $list[$key]['imageList'] = $val['images'] ? explode(',',$val['images']) : [];

                $list[$key]['create_time'] = $val['create_time'] ? date('Y-m-d H:i:s',$val['create_time']) : '';

            }

            $find['list'] = $list;

            return $find;

        } catch (\Exception $e) {

            $this->error = '获取失败';

            return [];

        }

    }



    public function getNumberOfPrompts(array $request): array

    {

        $shopIds = $request['shopIds'] ?? array();

        // print_r($shopIds);exit;;

        $where = [];

        array_push($where,['shop_id','in',$shopIds]);

        // 預警搜索

        $Ywhere = [];

        array_push($Ywhere,['early_warning','=',1]);

        array_push($Ywhere,['early_warning_result','=',0]);

        $Ywhere = array_merge($where,$Ywhere);

        // 追责搜索

        $Zwhere = [];

        array_push($Zwhere,['accountability','=',1]);

        array_push($Zwhere,['accountability_result','=',0]);

        $Zwhere = array_merge($where,$Zwhere);



        $Ynum  = Db::name('return_vist_t')->where($Ywhere)->count();

        $Znum  = Db::name('return_vist_t')->where($Zwhere)->count();

        // print_r(Db::name('return_vist_t')->getLastSql());exit;

        $dsWhere = [];

        $userInfo = $request['userInfo'];

        // if ($userInfo['group_id'] != 1){

        //     array_push($dsWhere,['user_id','=',$userInfo['id']]);

        // }

        array_push($dsWhere,['yjreturn_visit_time','>=',strtotime(date("Y-m-d").' 00:00:00')]);

        array_push($dsWhere,['yjreturn_visit_time','<=',strtotime(date("Y-m-d").' 23:59:59')]);

        $dsWhere = array_merge($where,$dsWhere);

        $dsNum  = Db::name('return_vist_ds')->where($dsWhere)->count();



        $list = [];



        // if ($Ynum){

            array_push($list,[

                'describe' => '您有'.$Ynum.'回访预警暂未处理，请及时处理',

                'type'     => 1,

                'num'      => $Ynum

            ]);

        // }



        // if ($Znum){

            array_push($list,[

                'describe' => '您有'.$Znum.'回访追责暂未处理，请及时处理',

                'type'     => 2,

                'num'      => $Znum

            ]);

        // }

            array_push($list,[

                'describe' => '您今日有'.$dsNum.'预约回访待处理，请及时处理',

                'type'     => 3,

                'num'      => $dsNum

            ]);

        $data['list'] = $list;

        return $data;

    }

}

